package com.ruoyi.system.listener;

import com.rabbitmq.client.Channel;
import com.ruoyi.common.core.constant.MailConstant;
import com.ruoyi.common.core.exception.GlobalException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.send.SendUtils;
import com.ruoyi.system.domain.SchoolRole;
import com.ruoyi.system.domain.vo.MailVo;
import com.ruoyi.system.service.ISchoolRoleService;
import net.bytebuddy.asm.Advice;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@ConfigurationProperties(prefix = "spring")
@RabbitListener(queues = {"mailQueue"})
public class RabbitListenerMailQueue {

    @Autowired
    ISchoolRoleService schoolRoleService;

    @Value("${spring.mail.username}")
    private String mainMail;

    @Autowired
    ThreadPoolTaskScheduler threadPoolTaskScheduler;


    @RabbitHandler
    public void mailQueueListen(MailVo mailVo, Channel channel, Message message) throws Exception {

        try{
            handle(mailVo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            e.printStackTrace();
        }
    }

    private void  handle(MailVo mailVo){
        Integer count = mailVo.getCount();
        if (count> MailConstant.MAX_SEND_COUNT){
            throw new GlobalException("发送次数不能超过"+MailConstant.MAX_SEND_COUNT+"次");
        }
        String ids = mailVo.getTos();
        String content = mailVo.getContent();
        Integer frequency = mailVo.getFrequency();
        Date startTime = mailVo.getStartTime();
        String[] idArray = ids.split(",");
        for (String s : idArray) {
            SchoolRole schoolRole = new SchoolRole();
            schoolRole.setUserId(Long.parseLong(s));
            List<SchoolRole> schoolRoles =
                    schoolRoleService.selectSchoolRoleList(schoolRole);
            schoolRole=schoolRoles.get(0);
            String email = schoolRole.getEmail();
            if (!StringUtils.isEmpty(email)){
                Object[] objects=new Object[5];
                objects[0]=content;
                objects[1]="您好！北京联合大学第二课堂活动平台正在向你发起通知：";
                objects[2]=",请及时查看通知,并进行相关事宜";
                objects[3]="Hello! The second classroom activity platform of Beijing Union University is sending you a notice:";
                objects[4]="";
                for (int i = 0; i < count; i++) {
                    //第一次直接startTime
                    if (i!=0){
                        //计算发送速度后的时间
                        double v=0.0;
                        if (frequency.equals(MailConstant.TIME0)){
                            v=MailConstant.Frequency.Time0.getTime();
                        } else if (frequency.equals(MailConstant.TIME1)){
                            v=MailConstant.Frequency.Time1.getTime();
                        }else if (frequency.equals(MailConstant.TIME2)){
                            v=MailConstant.Frequency.Time2.getTime();
                        }else if (frequency.equals(MailConstant.TIME3)){
                            v=MailConstant.Frequency.Time3.getTime();
                        }else if (frequency.equals(MailConstant.TIME4)){
                            v=MailConstant.Frequency.Time4.getTime();
                        }
                        long lastTimer= (startTime.getTime()+ Double.doubleToLongBits(v*60*60*1000));
//                        long lastTimer= (startTime.getTime()+ 60*1000);
                        startTime=new Date(lastTimer);
                    }
                    threadPoolTaskScheduler.schedule(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                SendUtils.sendHtmlEmailByUser(mainMail,email,"第二课堂活动平台通知",objects);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    },startTime);
                }
            }
        }
    }
}
